package cn.edu.swust.adressbook.service.impl;

import android.content.Context;

import java.util.List;

import cn.edu.swust.adressbook.bean.CallLog;
import cn.edu.swust.adressbook.bean.Contact;
import cn.edu.swust.adressbook.dao.CallLogDao;
import cn.edu.swust.adressbook.dao.ContactDao;
import cn.edu.swust.adressbook.utils.PinyinUtil;


public class ContactServiceImpl extends BaseServiceImpl<Contact> {
    public ContactServiceImpl(Context context) {
        super(context);
    }

    @Override
    public List<Contact> getAll() {
        return daoSession.getContactDao().queryBuilder().orderAsc(ContactDao.Properties.Pinyin).list();
    }

    @Override
    public long add(Contact contact) {
        contact.setPinyin(PinyinUtil.getPingYin(contact.getName()));
        return super.add(contact);
    }

    @Override
    public void update(Contact contact) {
        contact.setPinyin(PinyinUtil.getPingYin(contact.getName()));
        super.update(contact);
    }

    @Override
    public void delete(Contact contact) {
        deleteCallLog(contact.getId());
        super.delete(contact);
    }

    @Override
    public Contact get(Long id) {
        return daoSession.getContactDao().load(id);
    }

    private void deleteCallLog(long id) {
        List<CallLog> logs = daoSession.getCallLogDao().queryBuilder()
                        .where(CallLogDao.Properties.ContactId.eq(id))
                        .list();
        for (CallLog item : logs){
            daoSession.delete(item);
        }
    }
}
